/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.modbusServer.msg;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.msg.ModbusResponse;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 *
 * @author Rainbow
 */
public class SEWriteSingleRegisterResponse extends ModbusResponse {

    //instance attributes
    private int reference;
    private int registerValue;

    /**
     * Constructs a new <tt>WriteSingleRegisterResponse</tt>
     * instance.
     */
    public SEWriteSingleRegisterResponse() {
        super();
        setDataLength(4);
        setFunctionCode(Modbus.WRITE_SINGLE_REGISTER);
    }

    /**
     * Constructs a new <tt>WriteSingleRegisterResponse</tt>
     * instance.
     *
     * @param reference the offset of the register written.
     * @param value     the value of the register.
     */
    public SEWriteSingleRegisterResponse(int reference, int value) {
        super();
        setReference(reference);
        setRegisterValue(value);
        setDataLength(4);
        setFunctionCode(Modbus.WRITE_SINGLE_REGISTER);
    }



    /**
     * Returns the value that has been returned in
     * this <tt>WriteSingleRegisterResponse</tt>.
     * <p>
     *
     * @return the value of the register.
     */
    public int getRegisterValue() {
        return registerValue;
    }

    /**
     * Sets the value that has been returned in the
     * response message.
     * <p>
     *
     * @param value the returned register value.
     */
    private void setRegisterValue(int value) {
        registerValue = value;
    }

    /**
     * Returns the reference of the register
     * that has been written to.
     * <p>
     *
     * @return the reference of the written register.
     */
    public int getReference() {
        return reference;
    }

    /**
     * Sets the reference of the register that has
     * been written to.
     * <p>
     *
     * @param ref the reference of the written register.
     */
    private void setReference(int ref) {
        reference = ref;
        //setChanged(true);
    }

    @Override
    public void writeData(DataOutput dout) throws IOException {
        dout.write(getMessage());
    }

    @Override
    public void readData(DataInput din) throws IOException {
        setReference(din.readUnsignedShort());
        setRegisterValue(din.readUnsignedShort());
        //update data length
        setDataLength(4);
    }

    @Override
    public byte[] getMessage() {
        byte result[] = new byte[4];

        result[0] = (byte)((reference >> 8) & 0xff);
        result[1] = (byte)(reference & 0xff);
        result[2] = (byte)((registerValue >> 8) & 0xff);
        result[3] = (byte)(registerValue & 0xff);

        return result;
    }

    
}
